//
//  InviteCodeAlertView.swift
//  LeTu
//
//  Created by g1 on 2023/12/20.
//

import UIKit

class InviteCodeAlertView: UIView {

    private let rootView: UIWindow? = AppThemeManager.keyWindow()
    private var backgroundView: UIView = UIView()
    
    private var toWechatHolder: (() -> Void)?
    
    init(toWechatHolder: @escaping () -> Void) {
        
        super.init(frame: .zero)
        
        self.toWechatHolder = toWechatHolder
        
        guard rootView != nil else { return }
        configUI()
    
    }
    
    // MARK: - UIButtonAction
    @objc func toWechatBtnAction() {
        guard let handler = toWechatHolder else { return }
        handler()
    }
    @objc func hideAction() {
        hide()
    }
    
    // MARK: - configUI
    func configUI() {
        
        guard let rootView = rootView else { return }
        
        // 防止多个 AlertView 重复显示
        if rootView.subviews.filter({ $0.isKind(of: InviteCodeAlertView.self) }).count > 0 { return }
                
        backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        
        rootView.addSubview(backgroundView)
        rootView.addSubview(self)
        addSubview(backView)
        backView.addSubview(titleLabel)
        backView.addSubview(promptLabel)
        backView.addSubview(promptImgView)
        backView.addSubview(toWechatBtn)
        
        loadLayout()
        rootView.layoutIfNeeded()

    }
    func loadLayout() {
        
        guard rootView != nil else { return }
        
        backgroundView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        backView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(screenFixationWidth-120)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(34)
            make.right.equalTo(-34)
            make.top.equalTo(50)
            make.height.equalTo(22)
        }
        promptLabel.snp.makeConstraints { make in
            make.left.right.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(24)
        }
        promptImgView.snp.makeConstraints { make in
            make.left.right.equalTo(titleLabel)
            make.top.equalTo(promptLabel.snp.bottom).offset(22)
        }
        toWechatBtn.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(44)
            make.top.equalTo(promptImgView.snp.bottom).offset(22)
            make.height.equalTo(CGFloat.app_btnHeight)
            make.bottom.equalTo(-38)
        }
        
        toWechatBtn.addTarget(self, action: #selector(toWechatBtnAction))
        
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        backView.backgroundColor = .app_white
        backView.layer.cornerRadius = 12
        backView.clipsToBounds = true
        return backView
    }()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = kSetPingFangBlod(20)
        titleLabel.textAlignment = .center
        titleLabel.text = "邀请口令复制成功"
        titleLabel.textColor = UIColor(hex: 0x493528)
        return titleLabel
    }()
    private lazy var promptLabel: UILabel = {
        let promptLabel = UILabel()
        promptLabel.attributed.text = "\("1、选择微信好友或微信群 \n2、“黏贴”发送好友，好友也能得大额奖励", .paragraph(.lineSpacing(2)))"
        promptLabel.font = kSetPingFangMedium(14)
        promptLabel.textColor = UIColor(hex: 0x99693D)
        promptLabel.numberOfLines = 0
        return promptLabel
    }()
    private lazy var promptImgView: UIImageView = {
        let promptImgView = UIImageView()
        promptImgView.image = UIImage(named: "invite_copy_prompt")
        return promptImgView
    }()
    private lazy var toWechatBtn: GradientButton = {
        let toWechatBtn = GradientButton()
        toWechatBtn.setTitle("前往微信粘贴")
        toWechatBtn.setFont(kSetPingFangMedium(16))
        toWechatBtn.gradientColors = UIColor.app_themeGradientColors
        return toWechatBtn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension InviteCodeAlertView {
    
    func show() {
        
        guard rootView != nil else { return }
        
        self.layoutIfNeeded()
        toWechatBtn.layerCornerRadius(CGFloat.app_btnHeight/2)
        UIView.animate(withDuration: CGFloat.app_alertShowInterval-0.1) {
            self.backgroundView.backgroundColor = .app_customAlertBackgroundColor
        }
        UIView.animate(withDuration: CGFloat.app_alertShowInterval, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 20, options: UIView.AnimationOptions(rawValue: 0), animations: {
            self.backView.backgroundColor = UIColor.white.withAlphaComponent(1.0)
        })
        backView.addGradientLayer(gradientColors: [UIColor(red: 1, green: 0.976, blue: 0.914, alpha: 1), UIColor(red: 0.996, green: 0.953, blue: 0.835, alpha: 1)], gradientDirection: .vertically, startPoint: CGPoint(x: 0.25, y: 0.5), endPoint: CGPoint(x: 0.75, y: 0.5))

        let tapGR = UITapGestureRecognizer(target: self, action: #selector(hideAction))
        tapGR.delegate = self
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tapGR)
    }
    
    private func hide(completion: (() -> Void)? = nil) {
        
        UIView.animate(withDuration: CGFloat.app_alertHidenInterval, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions(rawValue: 0), animations: {
            self.titleLabel.alpha = 0
            self.backView.alpha = 0
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        }) { finished in
            guard finished else { return }
            self.removeInviteCodeAlertView()
        }
        
    }
    func removeInviteCodeAlertView() {
        self.backgroundView.removeFromSuperview()
        self.removeFromSuperview()
    }
        
}

extension InviteCodeAlertView: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if let view = touch.view, view.isDescendant(of: backView) {
            return false
        }
        return true
    }
    
}

